<template>
  <el-button type="success" :icon="Download" @click="handleExport"
    >导出
    <el-tooltip effect="dark" :content="props.msg">
      <el-icon class="ml-2"><InfoFilled /></el-icon>
    </el-tooltip>
  </el-button>
</template>

<script setup lang="ts">
import { Download } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";

const route = useRoute();
const props = defineProps({
  exportApi: {
    type: Function
  },
  queryform: {},
  downloadName: {
    default: ""
  },
  msg: {
    default: "默认导出全部数据，条件查询后只导出符合查询条件的数据"
  }
});

const handleExport = () => {
  const { exportApi, queryform, msg } = props;

  const name = props.downloadName || route.meta?.title || "";
  exportApi(queryform).then(res => {
    exportExcel(
      res,
      () => {
        ElMessage.success("导出成功");
      },
      name
    );
  });
};

const exportExcel = (res, callbak, name = "") => {
  if (!name) {
    name = dayjs(new Date()).format("YYYY-MM-DD");
  }
  const blob = new Blob([res], {
    type: "application/vnd.ms-excel;charset=utf-8"
  });
  const url = window.URL.createObjectURL(blob);
  const aLink = document.createElement("a");
  aLink.style.display = "none";
  aLink.href = url;
  aLink.setAttribute("download", `${name}.xlsx`);
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);
  window.URL.revokeObjectURL(url);
  if (callbak) {
    callbak();
  }
};
</script>
